package es.cea.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class libros
 */
@WebServlet("/libros")
public class libros extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
       HttpSession sesion = request.getSession();
       
       object obj = (object) sesion.getAttribute("admin");
       
       PrintWriter writer = response.getWriter();
       
     
		List<Stat> stats = (List<Stat>) request.getSession().getAttribute(
				"estadisticas");
		
		Stat stat = new Stat(request.getServletPath(),0);
		
		ArrayList<Stat> estadisticasSesion = (ArrayList<Stat>) sesion.getAttribute("estadisticas");
		if ( estadisticasSesion.contains(stat)){
			int indice = estadisticasSesion.indexOf(stat);
			int contador = estadisticasSesion.get(indice).contador + 1;
	
			estadisticasSesion.set(indice, new Stat(request.getServletPath(), contador));
		
			} else {
			estadisticasSesion.add(new Stat(request.getServletPath(), 1));
			}
		
			ArrayList<Stat> estadisticasContexto = (ArrayList<Stat>) request.getSession().getServletContext().getAttribute("estadisticasApp");
			
			if ( estadisticasContexto.contains(stat)){
			int indice = estadisticasContexto.indexOf(stat);
			int contador = estadisticasContexto.get(indice).contador + 1;
			
		     estadisticasContexto.set(indice, new Stat(request.getServletPath(), contador ));
			
			} else {
			estadisticasContexto.add(new Stat(request.getServletPath(), 1));
			}

	

			
    
      
    	   
	
		
		try
		{  
			Class.forName("com.mysql.jdbc.Driver");  
			Connection conexion = DriverManager.getConnection ("jdbc:mysql://localhost/libreria","root", "root");  
			Statement s = conexion.createStatement();  
			ResultSet rs = s.executeQuery ("select * from Libros");  
			while(rs.next()){
				
			  writer.println("<html><body><h4> Nombre del Libro " +  rs.getString(2) + "<a href= ./LibroDetail?id=" + rs.getString(1) + "> Detalles </a>" + "<a href= ./LibroEdit?id=" + rs.getString(1) + "&nbsp> Editar </a><br></body></html>");
			
			  
				
				
			}}
			catch (Exception e)  
			{  
			   e.printStackTrace();  
			}  
		
	
			
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
